const _ = require('lodash');
const LoopBackContext = require('loopback-context');
const services = require('../../services');

const eLancoService = services.eLanco;

module.exports = (ctx, modelInstance, callback) => {
  const context = LoopBackContext.getCurrentContext();
  const form = context.get('form');
  const flow = context.get('flow');
  const formDetail = context.get('formDetail');
  const approvalList = context.get('approvalList');
  const eventName = flow.flowRun.events.rejectAfter;
  const isCancel = false;
  if (_.isEmpty(eventName)) {
    if (flow.flowRun.isEmailSend) eLancoService.handlEmailSendEvent(form, flow, formDetail, approvalList, isCancel);
    return callback();
  }
  eLancoService.handleCustomEvent(form, formDetail, eventName, () => {
    callback();
    if (flow.flowRun.isEmailSend) eLancoService.handlEmailSendEvent(form, flow, formDetail, approvalList, isCancel);
  });
};
